package com.lagou.code;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import cn.hutool.json.JSONUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ZkJdbc {

    private static JDBCParam jdbcParam = new JDBCParam(
            "jdbc:mysql://linux123:3306/test?characterEncoding=utf-8&useSSL=false","root","12345678");
    private static Connection con =null;

    // 连接数据库
    public static void getNewConnection() throws SQLException {
        try {
            if(con!=null){
                // 当节点的数据变化时，需要关闭数据库的连接，创建新连接
                con.close();
            }
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(jdbcParam.getUrl() , jdbcParam.getName() , jdbcParam.getPassword());
            System.out.println("连接成功：host:"+jdbcParam.getUrl()+" name:"+jdbcParam.getName()+" password:"+jdbcParam.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException, SQLException {
        // 连接zookeeper
        ZkClient zkClient = new ZkClient("linux121:2181,linux122:2181");
        System.out.println("zkclient is ready");
        zkClient.setZkSerializer(new ZkStrSerializer());
        // 连接数据库
        getNewConnection();
        // 注册节点
        boolean exists = zkClient.exists("/jdbc");
        if(!exists){
            // JSONUtil.toJsonStr(jdbcParam) 是将 实例对象转换成 Json类型的字符串
            zkClient.createPersistent("/jdbc",JSONUtil.toJsonStr(jdbcParam));
        }

        // 监听节点
        zkClient.subscribeDataChanges("/jdbc", new IZkDataListener() {
            public void handleDataChange(String path, Object o) throws Exception {
                System.out.println(path+"data is changed"+o.toString());
                String s = o.toString();
                // JSONUtil.toBean(s, JDBCParam.class) 将字符串转换成JDBCParam实例
                JDBCParam newJdbc = JSONUtil.toBean(s, JDBCParam.class);
                jdbcParam.setPassword(newJdbc.getPassword());
                jdbcParam.setName(newJdbc.getName());
                jdbcParam.setUrl(newJdbc.getUrl());
                getNewConnection();
            }

            //数据节点删除
            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path+"data is delete");
            }
        });
        Thread.sleep(Integer.MAX_VALUE);
    }

}
